<script setup>
import { useRouter } from "vue-router";
import { ref, reactive, computed } from "vue";
import { showToast, showSuccessToast, showLoadingToast } from "@/utils/vant-ui";
import { useUserStore } from "@/store";
const router = useRouter();
// 表单数据
const form = reactive({
  topicName: "",
  topicType: null,
  content: "",
  topicFromId: useUserStore().user.id,
});

// 一级分类数据
const firstLevelTypes = ref([
  { id: 1, name: "生活日常" },
  { id: 2, name: "科技数码" },
  { id: 3, name: "娱乐休闲" },
  { id: 4, name: "学习交流" },
  { id: 5, name: "健康养生" },
]);

// 二级分类数据映射
const secondLevelMap = ref({
  1: [
    { id: 101, name: "美食分享", typeId: 1 },
    { id: 102, name: "旅行见闻", typeId: 2 },
    { id: 103, name: "家居生活", typeId: 3 },
    { id: 104, name: "情感交流", typeId: 4 },
  ],
  2: [
    { id: 201, name: "手机评测", typeId: 1 },
    { id: 202, name: "电脑硬件", typeId: 2 },
    { id: 203, name: "软件应用", typeId: 3 },
    { id: 204, name: "人工智能", typeId: 4 },
  ],
  3: [
    { id: 301, name: "影视推荐", typeId: 1 },
    { id: 302, name: "音乐分享", typeId: 2 },
    { id: 303, name: "游戏攻略", typeId: 3 },
    { id: 304, name: "体育赛事", typeId: 4 },
  ],
  4: [
    { id: 401, name: "学习方法", typeId: 1 },
    { id: 402, name: "书籍推荐", typeId: 2 },
    { id: 403, name: "学术讨论", typeId: 3 },
    { id: 404, name: "考试经验", typeId: 4 },
  ],
  5: [
    { id: 501, name: "健身运动", typeId: 1 },
    { id: 502, name: "饮食健康", typeId: 2 },
    { id: 503, name: "心理健康", typeId: 3 },
    { id: 504, name: "医疗知识", typeId: 4 },
  ],
});

// 选择器状态
const showFirstLevel = ref(false);
const showSecondLevel = ref(false);
const firstLevelSelected = ref(null);
const secondLevelSelected = ref(null);
const firstLevelDefaultIndex = ref(0);
const secondLevelDefaultIndex = ref(0);

// 计算二级分类列表
const secondLevelTypes = computed(() => {
  // console.log("二级分类列表", firstLevelSelected.value.id);
  if (!firstLevelSelected.value) return [];
  console.log(
    "二级分类列表",
    secondLevelMap.value[+firstLevelSelected.value.id],
  );
  return secondLevelMap.value[+firstLevelSelected.value.id] || [];
});

// 表单验证
const isFormValid = computed(() => {
  return (
    form.topicName.trim() && form.topicType !== null && form.content.trim()
  );
});

// 打开一级分类选择器
const showFirstLevelPicker = () => {
  showFirstLevel.value = true;
};

// 打开二级分类选择器
const showSecondLevelPicker = () => {
  if (!firstLevelSelected.value) {
    showToast("请先选择一级分类");
    return;
  }
  showSecondLevel.value = true;
};

// 一级分类确认
const onFirstLevelConfirm = ({ selectedOptions }) => {
  console.log("一级分类确认", selectedOptions);
  console.log("一级分类确认", selectedOptions[0]);
  firstLevelSelected.value = selectedOptions[0];
  firstLevelDefaultIndex.value = selectedOptions[0].id;
  showFirstLevel.value = false;
  // 重置二级选择
  secondLevelSelected.value = null;
  form.topicType = null;
};

// 二级分类确认
const onSecondLevelConfirm = ({ selectedOptions }) => {
  secondLevelSelected.value = selectedOptions[0];
  secondLevelDefaultIndex.value = selectedOptions[0].id;
  showSecondLevel.value = false;

  // 设置话题类型
  form.topicType = selectedOptions[0].typeId;
};

// 提交表单
const submitForm = async () => {
  await showLoadingToast({
    message: "发布中...",
    forbidClick: true,
    duration: 1000,
  });

  // 模拟API请求
  setTimeout(() => {
    // 打印当前填写的话题信息
    console.log("当前填写的话题信息", form);
    showSuccessToast("发布成功！");
    // 重置表单
    form.topicName = "";
    form.content = "";
    firstLevelSelected.value = null;
    secondLevelSelected.value = null;
    form.topicType = null;
    firstLevelDefaultIndex.value = 0;
    secondLevelDefaultIndex.value = 0;
    // router.push("/topic");
  }, 1500);
};
</script>
<template>
  <div class="app-container">
    <div class="header">
      <button class="back-btn" @click="router.back()">
        <van-icon name="arrow-left" size="20" />
      </button>
      <h1>发布新话题</h1>
    </div>

    <div class="form-container">
      <div class="form-group">
        <label class="form-label required">话题名称</label>
        <input
          type="text"
          class="topic-input"
          placeholder="请输入话题名称"
          v-model="form.topicName"
          maxlength="30"
        />
        <div
          class="character-count"
          :class="{ limit: form.topicName.length >= 30 }"
        >
          {{ form.topicName.length }}/30
        </div>
      </div>

      <div class="form-group">
        <label class="form-label required">话题类型</label>
        <div class="category-selector">
          <div
            class="category-btn"
            :class="{ active: showFirstLevel }"
            @click="showFirstLevelPicker"
          >
            {{ firstLevelSelected ? firstLevelSelected.name : "选择一级分类" }}
          </div>
          <div
            class="category-btn"
            :class="{ active: showSecondLevel }"
            @click="showSecondLevelPicker"
            :disabled="!firstLevelSelected"
          >
            {{
              secondLevelSelected ? secondLevelSelected.name : "选择二级分类"
            }}
          </div>
        </div>
      </div>

      <div class="form-group">
        <label class="form-label required">话题内容</label>
        <textarea
          class="topic-textarea"
          placeholder="请输入话题内容..."
          v-model="form.content"
          maxlength="500"
        ></textarea>
        <div
          class="character-count"
          :class="{ limit: form.content.length >= 500 }"
        >
          {{ form.content.length }}/500
        </div>
      </div>

      <button class="submit-btn" @click="submitForm" :disabled="!isFormValid">
        发布话题
      </button>
    </div>

    <div class="footer">
      <p>话题发布规范 | 用户协议 | 隐私政策</p>
      <p>© 2023 话题社区</p>
    </div>

    <!-- 一级分类选择器 - 添加field-names属性 -->
    <van-popup v-model:show="showFirstLevel" round position="bottom">
      <van-picker
        :columns="firstLevelTypes"
        :columns-field-names="{ text: 'name', value: 'id' }"
        @confirm="onFirstLevelConfirm"
        @cancel="showFirstLevel = false"
        :default-index="firstLevelDefaultIndex"
      />
    </van-popup>

    <!-- 二级分类选择器 - 添加field-names属性 -->
    <van-popup v-model:show="showSecondLevel" round position="bottom">
      <van-picker
        :columns="secondLevelTypes"
        :columns-field-names="{ text: 'name', value: 'id', typeId: 'typeId' }"
        @confirm="onSecondLevelConfirm"
        @cancel="showSecondLevel = false"
        :default-index="secondLevelDefaultIndex"
      />
    </van-popup>
  </div>
</template>
<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
    Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  background-color: #f7f8fa;
  color: #333;
  line-height: 1.5;
}

.app-container {
  max-width: 480px;
  margin: 0 auto;
  background: white;
  min-height: 100vh;
  position: relative;
}

.header {
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  color: white;
  padding: 20px 16px;
  text-align: center;
  position: relative;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

  h1 {
    font-size: 1.5rem;
    font-weight: 600;
    margin: 0;
  }
}

.back-btn {
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: white;
  font-size: 1.2rem;
  background: none;
  border: none;
  cursor: pointer;
}

.form-container {
  padding: 20px;
}

.form-group {
  margin-bottom: 24px;
  position: relative;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 15px;

  &.required::after {
    content: "*";
    color: #ee0a24;
    margin-left: 4px;
  }
}

.topic-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ebedf0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;

  &:focus {
    border-color: #1989fa;
    outline: none;
  }
}

.topic-textarea {
  width: 100%;
  min-height: 150px;
  padding: 12px 16px;
  border: 1px solid #ebedf0;
  border-radius: 8px;
  font-size: 16px;
  resize: vertical;
  transition: border-color 0.3s;

  &:focus {
    border-color: #1989fa;
    outline: none;
  }
}

.category-selector {
  display: flex;
  gap: 10px;
}

.category-btn {
  flex: 1;
  padding: 12px;
  background: white;
  border: 1px solid #ebedf0;
  border-radius: 8px;
  text-align: center;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;

  &.active {
    border-color: #1989fa;
    color: #1989fa;
    background-color: rgba(25, 137, 250, 0.1);
  }
}

.submit-btn {
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 14px;
  font-size: 16px;
  font-weight: 500;
  width: 100%;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 10px rgba(37, 117, 252, 0.3);

  &:active {
    transform: translateY(2px);
    box-shadow: 0 2px 5px rgba(37, 117, 252, 0.3);
  }

  &:disabled {
    background: #c8c9cc;
    box-shadow: none;
    cursor: not-allowed;
  }
}

.character-count {
  text-align: right;
  font-size: 12px;
  color: #969799;
  margin-top: 4px;

  &.limit {
    color: #ee0a24;
  }
}

.footer {
  text-align: center;
  padding: 20px;
  color: #969799;
  font-size: 12px;
}

@media (max-width: 480px) {
  .app-container {
    border-radius: 0;
  }
}
</style>
